<?php
namespace app\home\controller\system;

/*                .-~~~~~~~~~-._       _.-~~~~~~~~~-.
*             __.'              ~.   .~              `.__
*           .'//        保佑      \./        无bug      \\`.
*         .'//                     |                     \\`.
*       .'// .-~"""""""~~~~-._     |     _,-~~~~"""""""~-. \\`.
*     .'//.-"                 `-.  |  .-'                 "-.\\`.
*   .'//______.============-..   \ | /   ..-============.______\\`.
 .'______________________________\|/______________________________`.
     权限菜单控制器
 */
use app\common\controller\AdminController;
use think\App;
use think\facade\View;
use think\Request;

/**
 * Class Menu
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="菜单管理",auth=true)
 */
class Menu extends AdminController
{

    use \app\common\traits\Curd;


    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = app('app\common\model\system\SystemMenu');
        $this->auth = app('app\common\model\system\SystemAuth');
        $this->admin = app('app\common\model\system\SystemAdmin');
        $this->authNode = app('app\common\model\system\SystemAuthNode');
        $this->order = 'sort asc';
    }


    public function userInfo(Request $request)
    {

        //获取按钮级权限
        $info = $this->admin->find($request->param('accessToken'));
        if($info->id ==1){//为超级管理员时
            $permission = $this->model->column('name');
        }else{
            $nodes = $this->authNode->where('auth_id',$info->auth_ids)->column('node_id');
            $permission = $this->model->whereIn('id',$nodes)->column('name');
        }


        $data = [
            'avatar' => 'https://i.gtimg.cn/club/item/face/img/2/15922_100.gif' ,
            'permissions' => $permission ,
            'username' => $info->username,

        ];
        $data = [
            'code' => 200 ,
            'msg' => '正在请求中...' ,
            'data' => $data ,
        ];
        return json($data);
    }

    /**
     * 获取上级菜单
     * @param Request $request
     * @return \think\response\Json
     */
    public function getParent(Request $request)
    {
        $data = $this->model->select()->toArray();
        $data = $this->getListinfo($data , $pid = 0 , $result , $deep = 0);

        $otherData = [];
        foreach($data as $k=>$v){
            array_push($otherData,$v);
        }

        $data = [
            'code' => 200 ,
            'msg' => '正在请求中...' ,
            'data' => $otherData ,
        ];
        return json($data);
    }


    /**
     * 处理树形结构
     * @param $list
     * @param string $pk
     * @param string $pid
     * @param string $child
     * @param int $root
     * @return array
     */
    public function getListinfo($data , $pid = 0 , &$result = array() , $deep = 0)
    {
        $deep += 1;
        foreach ($data as $key => $val) {
            if ($pid == $val['pid']) {
                $result[$key]['title'] = str_repeat("----|" , $deep - 1) . $val['title'];
                $result[$key]['id'] = $val['id'];
                $result[$key]['pid'] = $val['pid'];

                $this->getListinfo($data , $val['id'] , $result , $deep);
            }
        }
        return $result;
    }

    /*获取路由权限菜单*/
    public function navigate()
    {
        //后台菜单
        $menus = $this->model->with(['children'=>function($query){
            $query->where(['status'=>1])->with(['children'=>function($query){
                $query->where(['status'=>1])->select();
            }]);
        }
        ])->where(['pid'=>0,'status'=>1])->order('id','asc')->select()->toArray();

        $data = [
            'code' => 200 ,
            'msg' => '正在请求中...' ,
            'data' => $menus ,
        ];
        return json($data);

    }

    public function getData()
    {
        if (method_exists($this , 'get_where')) {
            $where = $this->get_where($this->request->param() ?? []);
            $this->model = $this->model->where($where);
        }
        if (method_exists($this , 'get_with')) {
            $with = $this->get_with();
            $this->model = $this->model->with($with);
        }
        $this->request->filter(['strip_tags']);

        $res = $this->model->field($this->field ?? '*')
            ->order($this->order)->paginate($this->request->param('limit' , 1000));

        // $res = $model->order('id','desc')->paginate($request->param('limit',30));

        $data = [
            'code' => 0 ,
            'msg' => '正在请求中...' ,
            'count' => $res->total() ,
            'data' => $res->items() ,
        ];
        return json($data);
    }

    /**
     * 获取权限角色组
     * @param Request $request
     * @return \think\response\Json
     */
    public function getTree(Request $request)
    {
        $res = $this->auth->paginate($this->request->param('limit' , 10))->toArray();

        $data = [
            'code' => 200 ,
            'msg' => '正在请求中...' ,
            'totalCount' => $res['total'] ,
            'data' => [
                [
                    'id' => "root" ,
                    'label' => "全部角色" ,
                    'children' => $res['data']
                ]
            ] ,

        ];
        return json($data);
    }

    /**
     * 获取验证规则
     * @param $post
     * @return array
     */
    public function get_check_rule($post)
    {
        $rule = [
            'pid|上级菜单' => 'require' ,
            'type|类型' => 'require' ,
//                'icon|菜单图标'  => 'require',
            'path|路径url' => 'require|unique:system_menu,path,' . @$post['id'] . ',id' ,
            'name|名称' => 'require|unique:system_menu,name,' . @$post['id'] . ',id' ,
            'title|标题' => 'require|unique:system_menu,title,' . @$post['id'] . ',id' ,
        ];

        return $rule;
    }


    /**
     * @NodeAnotation(title="删除")
     */
    public function doDelete(Request $request)
    {
        $ids = $request->param('ids');

        is_array($ids) && $row = $this->model->whereIn('id', $ids)->select();
        !is_array($ids) && $row = $this->model->where('id', $ids)->select();
        empty($row) && $this->error('数据不存在');

        try {
            $save = $row->delete();
            $data = [
                'code' => 200 ,
                'msg' => '删除成功...' ,
            ];
        } catch (\Exception $e) {
            $data = [
                'code' => 202 ,
                'msg' =>  '删除失败' ,
                'error' =>$e->getMessage()
            ];
        }
        return json($data);
    }
}